<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属部门" prop="deptId">
        <treeselect style="width: 193px;" v-model="queryParams.deptId" :options="enabledDeptOptions" :show-count="true" placeholder="请选择部门" />
      </el-form-item>
      <el-form-item label="分类名称" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['store:classification:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['store:classification:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['store:classification:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['store:classification:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- <el-table v-loading="loading" :data="classificationList" @selection-change="handleSelectionChange"> -->
      <el-table
        v-loading="loading"
        :data="classificationList"
        row-key="classId"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
      <el-table-column type="selection" width="55" align="center" show-overflow-tooltip/>
      <el-table-column label="分类编号" align="center" prop="classId" show-overflow-tooltip/>
      <el-table-column label="部门" align="center" prop="deptName" show-overflow-tooltip/>
      <el-table-column label="排序" align="center" prop="sort" show-overflow-tooltip/>
      <el-table-column label="分类名称" align="center" prop="typeName" show-overflow-tooltip/>
      <el-table-column label="分类图片" align="center" prop="typeImg" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.typeImg"
            style="width: auto; height: 50px"
            :src="api + scope.row.typeImg"
          />
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['store:classification:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['store:classification:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属部门" prop="deptId">
          <treeselect style="width: 100%;" v-model="form.deptId" :options="enabledDeptOptions" :show-count="true" placeholder="请选择部门" />
        </el-form-item>
        <el-form-item label="分类名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" type="number" />
        </el-form-item>
        <el-form-item label="上级分类" prop="parentId">
          <el-select
            v-model="form.parentId"
            placeholder="请选择上级分类"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in typeList"
              :key="item.classId"
              :label="item.typeName"
              :value="item.classId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类图片" prop="typeImg">
          <el-upload
            class="upload-demo"
            :action="action"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            :limit="1"
            list-type="picture"
            :headers="headers"
            :on-exceed="handleExceed"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传1张jpg/png图片</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClassification, getClassification, delClassification, addClassification, updateClassification, queryTypeList } from "@/api/store/classification";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { deptTreeSelect } from "@/api/system/user";
import { getToken } from '@/utils/auth'
export default {
  name: "Classification",
  components: { Treeselect },
  data() {
    return {
      api: process.env.VUE_APP_BASE_API,
      action: '',
      headers: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品分类表格数据
      classificationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        typeName: null,
        typeImg: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
        typeName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        sort: [
            { required: true, message: "排序不能为空", trigger: "blur" }
        ],
        // typeImg: [
        //   { required: true, message: "分类图片不能为空", trigger: "blur" }
        // ],
        parentId: [{ required: true, message: "上级分类不能为空", trigger: "change" }]
      },
      enabledDeptOptions: [],
      typeList: [],
      fileList: []
    };
  },
  created() {
    this.action = process.env.VUE_APP_BASE_API + "/minio/upload"
    this.headers = { Authorization: "Bearer " + getToken() }
    this.getList();
    this.getDeptTree();
    this.getQueryTypeList()
  },
  methods: {
    /** 查询产品分类列表 */
    getList() {
      this.loading = true;
      listClassification(this.queryParams).then(response => {
        console.log(response)
        this.classificationList = this.handleTree(response.data, "classId");
        this.total = response.total || 0;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        classId: null,
        deptId: null,
        typeName: null,
        sort: 0,
        typeImg: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.resetForm("form");
      this.fileList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.classId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getQueryTypeList()
      this.reset();
      this.open = true;
      this.title = "添加产品分类";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const classId = row.classId || this.ids
      getClassification(classId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改产品分类";
        if(response.data.typeImg) {
          this.fileList = [
            {
              name: '图片1',
              url: process.env.VUE_APP_BASE_API + response.data.typeImg
            }
          ]
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.classId != null) {
            updateClassification(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClassification(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const classIds = row.classId || this.ids;
      this.$modal.confirm('是否确认删除产品分类编号为"' + classIds + '"的数据项？').then(function() {
        return delClassification(classIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('store/classification/export', {
        ...this.queryParams
      }, `classification_${new Date().getTime()}.xlsx`)
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
      });
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false;
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children);
        }
        return true;
      });
    },
    // 父级分类
    getQueryTypeList() {
      queryTypeList().then(res => {
        this.typeList = res.data;
      })
    },
    handleRemove(file, fileList) {
      this.form.typeImg = null
    },
    handleSuccess(file, fileList) {
      console.log(file, fileList,'ppppp22');
      this.form.typeImg = file.data.fileUrl
    },
    handleExceed(files, fileList) {
      this.$message.warning(`只能上传 1 张图片`);
    }
  }
};
</script>
